package com.im.common.toolkit.http;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

/**
 * @author gongym
 * @date 2018/12/1716:51
 */
class SslClientCustom {
  private static final String HTTP = "http";
  private static final String HTTPS = "https";
  private static SSLConnectionSocketFactory sslConnectionSocketFactory = null;
  private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = null;

  static {
    try {
      SSLContextBuilder sslContextBuilder =
          new SSLContextBuilder()
              .loadTrustMaterial(null, (X509Certificate[] x509Certificates, String s) -> (true));
      sslConnectionSocketFactory =
          new SSLConnectionSocketFactory(
              sslContextBuilder.build(),
              new String[] {"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"},
              null,
              NoopHostnameVerifier.INSTANCE);
      Registry<ConnectionSocketFactory> registryBuilder =
          RegistryBuilder.<ConnectionSocketFactory>create()
              .register(HTTP, new PlainConnectionSocketFactory())
              .register(HTTPS, sslConnectionSocketFactory)
              .build();
      poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registryBuilder);
      poolingHttpClientConnectionManager.setMaxTotal(500);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
      e.printStackTrace();
    }
  }

  /** 获取连接 */
  static CloseableHttpClient getHttpClient() {
    return HttpClients.custom()
        .setSSLSocketFactory(sslConnectionSocketFactory)
        .setConnectionManager(poolingHttpClientConnectionManager)
        .setConnectionManagerShared(true)
        .build();
  }
}
